package com.qujia.markert.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.qujia.common.exception.CustomException;
import com.qujia.coupon.domain.CouponUser;
import com.qujia.markert.domain.ReductionActivity;
import com.qujia.markert.domain.vo.CouponUserDto;
import com.qujia.markert.domain.vo.CouponUserVo;
import com.qujia.markert.mapper.ReductionActivityMapper;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.Oil;
import com.qujia.station.domain.Station;
import com.qujia.station.mapper.OilMapper;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IOilService;
import com.qujia.station.service.IStationService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qujia.markert.mapper.MarketCouponMapper;
import com.qujia.markert.domain.MarketCoupon;
import com.qujia.markert.service.IMarketCouponService;

import javax.annotation.Resource;

/**
 * 优惠劵管理Service业务层处理
 * 
 * @author qujia
 * @date 2020-12-22
 */
@Service
public class MarketCouponServiceImpl implements IMarketCouponService 
{
    @Autowired
    private MarketCouponMapper marketCouponMapper;

    @Resource
    private IStationService stationService;

    @Resource
    private IMarketCouponService marketCouponService;

    @Resource
    private IEnterpriseService enterpriseService;

    @Resource
    private OilMapper oilMapper;

    @Resource
    private ReductionActivityMapper reductionActivityMapper;



    /**
     * 查询优惠劵管理
     * 
     * @param couponId 优惠劵管理ID
     * @return 优惠劵管理
     */
    @Override
    public MarketCoupon selectMarketCouponById(Long couponId)
    {
        return marketCouponMapper.selectMarketCouponById(couponId);
    }

    /**
     * 查询优惠劵管理列表
     * 
     * @param marketCoupon 优惠劵管理
     * @return 优惠劵管理
     */
    @Override
    public List<MarketCoupon> selectMarketCouponList(MarketCoupon marketCoupon)
    {
        return marketCouponMapper.selectMarketCouponList(marketCoupon);
    }

    /**
     * 新增优惠劵管理
     * 
     * @param marketCoupon 优惠劵管理
     * @return 结果
     */
    @Override
    public int insertMarketCoupon(MarketCoupon marketCoupon)
    {
        return marketCouponMapper.insertMarketCoupon(marketCoupon);
    }

    /**
     * 修改优惠劵管理
     * 
     * @param marketCoupon 优惠劵管理
     * @return 结果
     */
    @Override
    public int updateMarketCoupon(MarketCoupon marketCoupon)
    {
        return marketCouponMapper.updateMarketCoupon(marketCoupon);
    }

    /**
     * 批量删除优惠劵管理
     * 
     * @param couponIds 需要删除的优惠劵管理ID
     * @return 结果
     */
    @Override
    public int deleteMarketCouponByIds(Long[] couponIds)
    {
        return marketCouponMapper.deleteMarketCouponByIds(couponIds);
    }

    /**
     * 删除优惠劵管理信息
     * 
     * @param couponId 优惠劵管理ID
     * @return 结果
     */
    @Override
    public int deleteMarketCouponById(Long couponId)
    {
        return marketCouponMapper.deleteMarketCouponById(couponId);
    }

    @Override
    public List<CouponUserVo> getCouponList(String mobilePhone, String oilName, String stationId,
                                          BigDecimal amt, BigDecimal reductionAmount, Integer activityId) {
        if(Objects.isNull(reductionAmount)){
            reductionAmount = BigDecimal.ZERO;
        }
        Station station = stationService.selectStationById(Long.valueOf(stationId));
        Enterprise enterprise = new Enterprise();
        enterprise.setEnterpriseId(station.getEnterpriseId());
        List<Enterprise> enterprises = enterpriseService.selectEnterpriseList(enterprise);
        if(CollectionUtils.isEmpty(enterprises)){
            throw new CustomException("油企不存在");
        }
        String couponEnabledFlag = enterprises.get(0).getCouponEnabledFlag();
        List<CouponUserVo> couponList = new ArrayList<CouponUserVo>();
        //油企是否开通享受优惠券
        if("1".equals(couponEnabledFlag)){
            CouponUserVo couponUser = null;
            couponUser = new CouponUserVo();
            couponUser.setEnterpriseId(station.getEnterpriseId().intValue());
            couponUser.setMobilePhone(mobilePhone);
            Oil oil = oilMapper.selectOilByName(oilName);
            couponUser.setOilId(String.valueOf(oil.getOilId()));
            couponUser.setStationId(Integer.valueOf(stationId));
            couponUser.setCouponThresholdAmt(new BigDecimal(amt.toString()));

            amt = amt.subtract(reductionAmount);
            couponList = marketCouponMapper.selectUsefulCoupon(couponUser);


            if (activityId != null) {
                //查活动信息
                ReductionActivity reductionActivity = reductionActivityMapper.selectReductionActivityById(Long.valueOf(activityId));

                if (reductionActivity.getActivityRule().equals("1")) {
                    //立减活动不强制，可以查询不互斥的优惠券
                    couponUser.setActivityFlag("0");//已经有立减活动，查询不互斥的优惠券
                    couponList = marketCouponMapper.selectUsefulCoupon(couponUser);
                }
            } else {
                couponList = marketCouponMapper.selectUsefulCoupon(couponUser);
            }


            if(couponList != null && couponList.size() > 0){
                for (CouponUserVo user : couponList) {
                    if(user.getCouponType().equals("1")){
                        //现金
                        user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt()));
                    }else if(user.getCouponType().equals("2")){
                        //折扣
                        user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt().multiply(new BigDecimal(amt.toString())).divide(new BigDecimal(100), 2)));
                    }
                    if(user.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
                        user.setNewAmtByCoupon(new BigDecimal("0.01"));
                    }
                }

                Collections.sort(couponList, new Comparator<CouponUserVo>() {
                    @Override
                    public int compare(CouponUserVo o1, CouponUserVo o2) {
                        //升序
                        return o1.getNewAmtByCoupon().compareTo(o2.getNewAmtByCoupon());
                    }
                });
            }

        }

        return couponList;
    }

    @Override
    public CouponUserDto getMaxCouponUserIdAndAmt(List<CouponUserVo> couponList,BigDecimal amt) {

        BigDecimal couponAmt;
        Integer couponUserId;
        CouponUserDto couponUserDto = new CouponUserDto();
        HashMap<Integer, BigDecimal> couponAmtMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(couponList)) {
            for (CouponUserVo couponUserVo : couponList) {
                if ("1".equals(couponUserVo.getCouponType())) {
                    couponAmtMap.put(couponUserVo.getCouponUserId(), couponUserVo.getCouponAmt());
                } else if ("2".equals(couponUserVo.getCouponType())) {
                    couponAmtMap.put(couponUserVo.getCouponUserId(), couponUserVo.getCouponAmt().multiply(amt).divide(new BigDecimal("100")));
                }
            }

            List<Map.Entry<Integer, BigDecimal>> res = couponAmtMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList());

            couponAmt = res.get(0).getValue();
            couponUserId = res.get(0).getKey();


            couponUserDto.setCouponUserId(couponUserId);
//            if("1".equals(couponUserDto.getCouponType())){
//                couponUserDto.setCouponAmt(couponAmt);
//            } else if ("2".equals(couponUserDto.getCouponType())) {
//                couponUserDto.setCouponAmt(couponAmt.multiply(amt).divide(new BigDecimal("100")));
//            }
            couponUserDto.setCouponAmt(couponAmt);
            return couponUserDto;
        }
        return couponUserDto;
    }

}
